import tkinter as tk
from tkinter import ttk

from serial_comm import SerialComm


class SerialSettingsFrame(ttk.LabelFrame):
    def __init__(self, master, serial_comm: SerialComm, on_open_callback=None):
        super().__init__(master, text="串口设置")
        self.serial_comm = serial_comm
        self.on_open_callback = on_open_callback
        self.port_var = tk.StringVar()
        self.baud_var = tk.StringVar(value="9600")
        self.is_open = False
        self._build_ui()
        self.refresh_ports()

    def _build_ui(self):
        ttk.Label(self, text="端口:").grid(row=0, column=0, padx=5, pady=5)
        self.port_combo = ttk.Combobox(self, textvariable=self.port_var, width=12)
        self.port_combo.grid(row=0, column=1, padx=5, pady=5)
        ttk.Label(self, text="波特率:").grid(row=0, column=2, padx=5, pady=5)
        self.baud_combo = ttk.Combobox(self, textvariable=self.baud_var, values=["9600","4800","19200","38400","57600","115200"], width=10)
        self.baud_combo.grid(row=0, column=3, padx=5, pady=5)
        self.refresh_btn = ttk.Button(self, text="刷新", command=self.refresh_ports)
        self.refresh_btn.grid(row=0, column=4, padx=5, pady=5)
        self.open_btn = ttk.Button(self, text="打开串口", command=self.toggle_port)
        self.open_btn.grid(row=0, column=5, padx=5, pady=5)

    def refresh_ports(self):
        ports = self.serial_comm.list_ports()
        self.port_combo['values'] = ports
        if ports:
            self.port_var.set(ports[0])
        else:
            self.port_var.set("")

    def toggle_port(self):
        if not self.is_open:
            try:
                self.serial_comm.open(self.port_var.get(), int(self.baud_var.get()))
                self.is_open = True
                self.open_btn.config(text="关闭串口")
                if self.on_open_callback:
                    self.on_open_callback(True)
            except Exception as e:
                show_toast(self, f"打开串口失败: {e}", 2000)
        else:
            self.serial_comm.close()
            self.is_open = False
            self.open_btn.config(text="打开串口")
            if self.on_open_callback:
                self.on_open_callback(False)

def show_toast(master, msg, duration=2000):
    toast = tk.Toplevel(master)
    toast.overrideredirect(True)
    toast.attributes("-topmost", True)
    label = tk.Label(toast, text=msg, bg="#333", fg="white", padx=20, pady=10, font=("微软雅黑", 12))
    label.pack()
    toast.update_idletasks()
    x = master.winfo_rootx() + (master.winfo_width() - toast.winfo_width()) // 2
    y = master.winfo_rooty() + (master.winfo_height() - toast.winfo_height()) // 2
    toast.geometry(f"+{x}+{y}")
    toast.after(duration, toast.destroy) 